<template>
	<div class="container">
		<view class="fliter">
			<view class="input-box single-input flex-space-between">
				<view class="item flex-center">
					<u-search :clearabled="true" bg-color="transparent" :show-action="false" v-model="query.serialno"
						placeholder="请输入机具号" @search="search"></u-search>
					<!-- <text class="iconfont icon-saoma" @click.stop="scanCode"></text> -->
				</view>
			</view>
		</view>
		<view class="nav-box">
			<text :class="{ active: navIndex == index }" @click="changeNav(index)" v-for="(item, index) in navList"
				:key="index">{{ item.title }}</text>
		</view>
		<view class="termial-box">
			<view class="total flex-space-between" style="margin-bottom: 10px;">
				<view class="num">
					共计
					<text class="blue">{{ totalNum }}</text>
					台
				</view>
				<view class="filter flex" @click="filterShow = true">
					<view class="btn2">
						筛选
						<text class="iconfont icon-down"></text>
					</view>
				</view>
			</view>

			<!-- <template v-if="list.length"> -->
			<view class="t-item" v-model="item.checked" v-for="(item, index) in list" :key="index"
				@click.stop="toDetail(item)">
				<view class="t-info">
					<view class="flex-space-between" style="padding: 15px;border-bottom: 1px solid #eee;">
						<u-cell-item :arrow="false" hover-class="none" :border-bottom="false" title="机具SN号："
							:value="item.serialno" class="title" />
						<!-- 代理商解绑 -->
						<!--
						<view class="btn-box" v-if="item.bindStatus == 1 && routeType != 'pre'">
							<view class="unBind" @click.stop="unBind(item)">解绑</view>
						</view>
						-->
						<!-- <view class="btn-box" v-if="item.bindStatus == 0 && routeType != 'pre'" @click.stop="toIdentification(item)">
							商户注册
						</view> -->
						<view style="min-width: 60px;margin-right: -5px;text-align: right;" :style="item.bindStatus == 0 ?unbindStyle:bindStyle">{{item.bindStatus == 0 ? "待绑定" : "已绑定" }}</view>
					</view>
					<view style="padding: 15px;">
						<!-- <u-cell-item :arrow="false" hover-class="none" :border-bottom="false" title="绑定状态："
							:value="item.bindStatus == 0 ? '待绑定' : '已绑定'" :value-style="item.bindStatus == 0 ?unbindStyle:bindStyle" /> -->
						<u-cell-item :arrow="false" hover-class="none" :border-bottom="false" title="产品政策："
							:value="item.policyName" />
								<u-cell-item :arrow="false" hover-class="none" :border-bottom="false" title="通讯费："
									:value="item.commFee" />
						
						<u-cell-item :arrow="false" hover-class="none" :border-bottom="false" title="服务费："
							:value="item.serviceFee"  />
						
						<view class="purple-bg" >
						<u-cell-item :arrow="false" hover-class="none" :border-bottom="false" title="代理商："
							:value="item.agentName+'('+item.agentNo+')'" />
						</view>
							<u-cell-item :arrow="false" hover-class="none" :border-bottom="false" title="品牌名称："
								:value="item.brandName" />
					</view>
					<view class="register-btn-box"v-if="item.bindStatus == 0 && routeType != 'pre'">
						<view class="btn-box" style="margin-right: 20rpx;" v-if="item.bindStatus == 0 && routeType != 'pre'" @click.stop="displayIdentificationQRCode(item)">
							机具二维码
						</view>
						<view class="btn-box" v-if="item.bindStatus == 0 && routeType != 'pre'" @click.stop="toIdentification(item)">
							商户注册
						</view>
					</view>
					
				</view>
				
			</view>
			<uni-load-more :status="loadMore"></uni-load-more>
			<!-- </template> -->
		</view>
		<u-popup v-model="filterShow" mode="top" :border-radius="20">
			<div class="filter-body">
				<div class="filter-content">
					<u-field :disabled="true" label="产品政策：" :value="query.policyName" :label-width="150"
						input-align="left" placeholder="请选择" >
						<text class="iconfont icon-Downarrow-R iconfont-right" slot="right" @click="showPicker = true"></text>
					</u-field>
					<u-field :disabled="true" label="查询范围：" :value="agentTypeName" :label-width="150" input-align="left"
						placeholder="请选择" >
						<text class="iconfont icon-Downarrow-R iconfont-right" slot="right" @click="showPicker2 = true"></text>
					</u-field>
					<u-field label="代理商编号：" v-model="query.agentNo" :label-width="180" input-align="left"
						placeholder="请输入"></u-field>
					<!-- <u-field
            :disabled="true"
            label="品牌："
            :value="query.brandName"
            input-align="left"
            :label-width="150"
            placeholder="请选择"
            @click="showPicker = true"
          >
            <text class="iconfont icon-Downarrow-R iconfont-right" slot="right"></text>
          </u-field> -->
				</div>
				<div class="footer-btn">
					<div class="btn-left"><button class="reset" size="large" type="warn"
							@click="resetHandle">重置</button></div>
					<div class="btn-right"><button class="myBtn" round size="large" @click="queryHandle">搜索</button>
					</div>
				</div>
			</div>
		</u-popup>

		<u-picker title="政策" v-model="showPicker" mode="selector" :range="policyList" range-key="policyName"
			confirm-color="#4888FB" @confirm="onConfirm" @cancel="showPicker = false" />
		<u-picker title="查询范围" v-model="showPicker2" mode="selector" :range="agentTypeList" range-key="text"
			confirm-color="#4888FB" @confirm="onConfirm2" @cancel="showPicker2 = false" />
			<u-popup v-model="showQR" mode="center">
				<canvas id="qrcode" canvas-id="qrcode" style="width: 200px;height: 200px;"></canvas>
			</u-popup>
	</div>
</template>

<script>
	import loadMoreData from '@/mixins/loadmore';
	import UQRCode from 'uqrcodejs';
	import {
		termList,
		termUnBind,
		preTermList,
		getLoginSn,
		getTermQRCode
	} from '_a/terminal';

	export default {
		mixins: [loadMoreData],
		data() {
			return {
				query: {
					policyCode: this.$store.getters.policyList[0].policyCode
				},
				list: [],
				selectCheckbox: [],
				type: 2,
				pList: [{
						text: '回拨给平台',
						value: 0
					},
					{
						text: '回拨给上级',
						value: 1
					}
				],
				showAction: false,
				showPicker: false,
				showQR: false,
				navIndex: 0,
				navList: [{
					title: '全部',
					value: ''
				}, {
					title: '已绑定',
					value: '1'
				}, {
					title: '未绑定',
					value: '0'
				}],
				agentTypeList: [{
						text: '团队',
						value: 1
					},
					{
						text: '自己',
						value: 2
					}
				],
				filterShow: false,
				typename: '全部',
				agentTypeName: '团队',
				totalNum: 0,
				pageSize: 20,
				agentType: 1,
				showPicker2: false,
				bindStyle:{color:'#4cd964'},
				unbindStyle:{color:'#dd524d'},
				qrCodeUrl: '',
			};
		},
		computed: {
			policyList() {
				return this.$store.getters.policyList || [];
			},
			agentLevel() {
				return this.$store.getters.user.agentLevel || 2
			}
		},
		onLoad(o) {
			this.navIndex = o.type || 0;
			this.routeType = o.routeType || 'default'; //pre 平行代理进来的  default 普通进来的
			this.query.policyCode = o.policyCode;
			let item = this.policyList.find(item => item.policyCode == o.policyCode);
			if (item) {
				this.query.policyName = item.policyName;
			}
			if (o.type) {
				this.query.bindStatus = this.navList[this.navIndex].value;
			} else {
				this.query.bindStatus = '';
			}
			this.getList();
		},
		onNavigationBarButtonTap() {
			this.$nav.push({
				path: '/pages/home/trading/operation'
			});
		},
		
		methods: {
			createQR(path) {
				// 获取uQRCode实例
				var qr = new UQRCode();
				// 设置二维码内容
				qr.data = path;
				// 设置二维码大小，必须与canvas设置的宽高一致
				qr.size = 200;
				// 调用制作二维码方法
				qr.make();
				// 获取canvas上下文
				var canvasContext = uni.createCanvasContext('qrcode', this); // 如果是组件，this必须传入
				// 设置uQRCode实例的canvas上下文
				qr.canvasContext = canvasContext;
				// 调用绘制方法将二维码图案绘制到canvas上
				qr.drawCanvas();
			},
			displayIdentificationQRCode(item) {
				getTermQRCode(item.serialno).then(res => {
					if (res.code === 200) {
						this.showQR = true;
						setTimeout(()=> {
							this.createQR(res.msg)
						}, 500);
					}else{
						this.$toast({
							message: '获取机具二维码失败！'
						});
					}
				});
			},
			toIdentification(item) {
				getLoginSn(item.serialno).then(res => {
					if (res.code === 200) {
						this.$nav.push({
							path: '/pages/home/identification/index',
							query:{sn:res.msg}
						}); 
					}else{
						this.$toast({
							message: '获取机具号失败！'
						});
					}
				});
			},
			
			toDetail(item) {
				this.$storage.setStore('termDetailInfo', item);
				this.$nav.push({
					path: '/pages/home/terminal/terminalInfo'
				});
			},
			getList() {
				let params = {
					pageNum: this.pageNum,
					pageSize: this.pageSize,
					agentType: this.agentType,
					...this.query
				};
				switch (this.routeType) {
					case 'pre': //平行代理进入
						preTermList(params).then(res => {
							var list = res.rows;
							this.totalNum = res.total;
							this.loadMoreStatusDeal(list);
							if (list.length > 0) {
								this.list = this.list.concat(list);
							}
						});
						break;
					case 'default':
						termList(params).then(res => {
							var list = res.rows;
							this.totalNum = res.total;
							this.loadMoreStatusDeal(list);
							if (list.length > 0) {
								this.list = this.list.concat(list);
							}
						});
						break;
					default:
						break;
				}
			},
			unBind(item) {
				this.$tip.modal({
					content: '您确定要解绑吗?'
				}).then(res => {
					console.log(res);
					termUnBind([{
						serialno: item.serialno
					}]).then(res2 => {
						this.$tip.toast(res2.msg);
						this.init();
					});
				});
			},
			init() {
				this.$nextTick(() => {
					this.list = [];
					this.refreshLoad();
				});
			},
			resetHandle() {
				this.typename = '全部';
				this.query = {
					pageNum: 1,
					pageSize: 20
				};
			},
			queryHandle() {
				this.$forceUpdate();
				this.init();
				this.filterShow = false;
			},
			changeNav(i) {
				this.query.bindStatus = this.navList[i].value;
				this.navIndex = i;
				this.init();
			},
			scanCode(type) {
				let _this = this;
				// this.$tip.loading('识别中....')
				// #ifdef H5
				this.$tip.toast('暂不支持!');
				// #endif
				// #ifndef H5
				uni.scanCode({
					success(res) {
						_this.$tip.loaded();
						_this.$tip.toast('识别成功!');
						_this.query.serialno = res.result;
						this.init();
					},
					fail() {
						_this.$tip.loaded();
					}
				});
				// #endif
			},
			clickItem(e) {
				console.log(e);
				this.query.pType = this.pList[e].value;
				this.query.pTypeName = this.pList[e].text;
			},
			onConfirm(e) {
				console.log(e);
				this.query.policyCode = this.policyList[e[0]].policyCode;
				this.query.policyName = this.policyList[e[0]].policyName;
				// this.chooseIndex = e[0];
			},
			onConfirm2(e) {
				this.query.agentType = this.agentTypeList[e[0]].value;
				this.agentTypeName = this.agentTypeList[e[0]].text;
				// this.chooseIndex = e[0];
			},
			chagneActive(item) {
				// item.isActive = !item.isActive
				this.$forceUpdate();
			},
			reachBottomCallBack() {
				this.getList();
			},
			search() {
				this.init();
			},
			issuedHandle() {
				/** 下发机具 **/
				if (this.selectCheckbox.length > 0) {
					if (this.type == 1) {
						if (this.orderId) {
							// this.issuedOrder();
							this.submitPopup = true;
						} else {
							this.checkOrder();
							// this.$dialog
							//   .confirm({
							//     message:
							//       "机具通过机具管理下发给下级， 不能自动升级代理商身份，必须要通过采购下单，才能自动升级,是否继续下发?",
							//     confirmButtonColor: "#1989fa",
							//   })
							//   .then(() => {
							//     this.checkOrder();
							//   })
							//   .catch(() => {
							//     // on cancel
							//   });
						}
					} else {
						this.$dialog
							.confirm({
								message: '您确定要回拨SN号吗'
							})
							.then(() => {
								termReturn(this.selectCheckbox.map(item => item.id)).then(res => {
									if (res.code === 200) {
										this.$toast({
											message: '回拨成功'
										});
										this.list = [];
										this.selectCheckbox = [];
										this.query.pageNum = 1;
										this.query.pageSize = 999999;
										this.queryMethod();
									}
								});
							})
							.catch(() => {
								// on cancel
							});
					}
				} else {
					this.$toast({
						message: this.type == 1 ? '请选择下发机具' : '请选择回拨SN号'
					});
				}
			}
		}
	};
</script>
<style scoped lang="scss">
	.container {
		padding: R(30) 0 R(140);
	}

	.fliter {
		margin: 0 R(25);

		.single-input {
			flex-wrap: wrap;
			align-items: center;

			.item {
				background: #fff;
				width: 100%;
				padding-right: R(30);
				padding-left: R(10);
				height: R(80);
				background: #ffffff;
				border-radius: R(10);
				margin-bottom: R(30);

				.icon-saoma {
					color: $themeColor;
				}
			}
		}
	}

	.nav-box {
		margin: 0 R(23) R(30);

		text {
			width: R(124);
			height: R(56);
			line-height: R(56);
			background: #ffffff;
			border-radius: R(30);
			display: inline-block;
			color: #1a1a1a;
			text-align: center;
			font-size: $uni-font-size-sm;
			margin-right: R(20);
		}

		.active {
			border: 1px solid $themeColor;
			// color: #4286f5;
			color: $themeColor;
			background: #d9e7ff;
			// border-bottom-right-radius: R(20);
		}
	}

	.termial-box {
		// margin: 0 R(25);
		// background: #fff;
		// border-radius: R(10);
		padding: R(26) R(30);

		.total {
			margin-bottom: R(20);
			font-size: R(24);

			.num {
				font-weight: 400;
				color: #737373;

				.blue {
					color: $themeColor;
				}
			}

			.filter {
				color: #8c8c8c;

				.btn1 {
					margin-right: R(20);
				}

				.icon-down {
					font-size: R(20);
				}
			}
		}

		/deep/.u-checkbox-group {
			width: 100%;
		}

		.t-item {
			width: 100%;
			// border-bottom: 1px solid #eee;
			background: #fff;
			border-radius: $uni-border-radius-lg;
			margin-bottom: $uni-spacing-col-lg;
			// position: relative;

			.title {
				font-size: $uni-font-size-base;
				font-weight: bold;
				color: #1a1a1a;
				padding: $uni-spacing-row-base;

				/deep/.u-cell__value {
					color: #1a1a1a;
				}
			}

			/deep/.u-cell {
				padding: R(8) R(0);

				.u-cell__value {
					text-align: left;
				}
			}
			.register-btn-box{
				padding: $uni-spacing-row-lg;
				border-top: 1px solid #ddd;
				display: flex;
				justify-content: end;
			}

			.btn-box {
				width: R(160);
				height: R(50);
				line-height: R(50);
				// background: #d9e7ff;
				border-radius: R(30);
				// color: #4286f5;
				color: #fff;
				background: $button-linear-bg;
				text-align: center;
				display: inline-block;
				// position: absolute;
				right: R(10px);
				top: 43%;
				font-size: $uni-font-size-sm;
				.unBind{
					font-size: $uni-font-size-sm;
				}
			}
		}
	}

	.filter-body {
		padding: R(30);
	}

	.filter-content {
		margin-bottom: R(30);
	}

	.filter-body .footer-btn {
		display: flex;
		/*position: absolute;*/
		bottom: 0;
		width: 100%;
	}

	.filter-body .footer-btn .btn-left {
		width: 30%;
		margin-left: 15%;
	}

	.filter-body .footer-btn .btn-right {
		width: 30%;
		margin-left: 10%;
	}

	.filter-body .filter-tiem {
		margin-bottom: R(25);
	}

	.filter-body .filter-tiem .tit {
		font-size: R(32);
		color: #333;
	}

	.filter-body .filter-tiem .select-list .select-item {
		float: left;
		width: 33%;
		padding: R(20) R(10);
	}
</style>